package cn.com.headfree.task;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.com.headfree.ftp.FTPClientFactory;
import cn.com.headfree.ftp.FTPPoolUtils;

@Component
public class BusinessListenerTask {

	private static final Logger log = Logger.getLogger(BusinessListenerTask.class);
	// 用户日志本地log目录
	@Value("${ftp.localDir.login}")
	private String userLocalLogDir;

	@Value("${ftp.localDir.menu}")
	private String menuLocalLogDir;
	
	@Value("${ftp.ftpFileDir}")
	private String ftpFileDir;

	/**
	 * 向ftp服务器传输文件
	 */
	@Scheduled(cron = "0 0 6 * * ?")
	public void upload() {
		log.info("*******************************日志开始同步*****************************");
		String[] keyname = ftpFileDir.split(",");
		// 获取文件map-默认目录下没有文件夹
		Map<String, List<File>> needFtpFile = getNeedFtpFiles(keyname, userLocalLogDir, menuLocalLogDir);
		FTPClient fTPClient = null;
		String hostAddress;
		try {
			hostAddress = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e1) {
			log.info("获取应用服务的ip地址出现了异常，同步结束！");
			return;
		}
		List<String> fileNames = null;
		for (String key : keyname) {
			int randCount = 0;
			int randNum = -1;
			while (randCount < 3) {
				try {
					if (randNum < 0) {
						randNum = RandomUtils.nextInt(5);
					} else {
						randNum = randNum + 5;
					}
					log.info("randNum的值是：" + randNum + "randCount：" + randCount + ",同步的文件夹名称：" + key);
					Thread.sleep(randNum * 60 * 1000);
					fTPClient = FTPPoolUtils.getInstance().getFTPClient();
					// 获取ftp上指定目录下的文件名集合
					fileNames = FTPPoolUtils.getInstance().getFileNames(key);
					FTPPoolUtils.getInstance().changeFileDir(key);
					List<File> files = needFtpFile.get(key);
					if (files != null) {
						for (File file : files) {
							// 获取本地文件名
							String fileName = file.getName();
							// 将ip地址家在文件名前
							fileName = hostAddress + "_" + fileName;
							if (!fileNames.contains(fileName)) {
								int updateCount = 0;
								while (updateCount < 3) {
									log.info("上传的文件名：" + fileName);
									boolean updateFlag = FTPPoolUtils.getInstance().uploadFile(fileName,file.getPath());
									if (updateFlag) {
										break;
									} else {
										log.error("上传至ftp服务器失败,上传次数：" + updateCount + ",文件名:" + file.getName());
										updateCount++;
									}
								}
							}
						}
					} else {
						log.error("没有可以同步的文件");
					}
					break;
				} catch (Exception e) {
					log.error("上传至ftp异常，randCount=" + randCount, e);
					randCount++;
				} finally {
					log.info("*******************************销毁ftp客户端,ftpClient***********************");
					if (fTPClient != null) {
						FTPClientFactory factory = FTPPoolUtils.getInstance().getFactory();
						if (factory != null) {
							try {
								factory.destroyObject(fTPClient);
								log.info("销毁ftp客户端成功");
							} catch (Exception e) {
								log.error("销毁ftp客户端异常", e);
							}
						}
					}
				}
			}
		}
		log.info("*******************************日志同步完成*****************************");
	}

	/**
	 * 获取需要上传到ftp服务器的文件-名称包含前一天日期的文件
	 *
	 * @param
	 * @return
	 */
	private Map<String, List<File>> getNeedFtpFiles(String[] keyname, String userLocalLogDir, String menuLocalLogDir) {
		Map<String, List<File>> fileMap = new HashMap<String, List<File>>();
		File userFile = new File(userLocalLogDir);
		File menuFile = new File(menuLocalLogDir);

		File[] userFiles = userFile.listFiles();
		File[] menuFiles = menuFile.listFiles();

		if (userFiles != null) {
			List<File> files = new ArrayList<File>(userFiles.length);
			for (File fl : userFiles) {
				files.add(fl);
			}
			fileMap.put(keyname[0], files);
		}

		if (menuFiles != null) {
			List<File> files = new ArrayList<File>(menuFiles.length);
			for (File fl : menuFiles) {
				files.add(fl);
			}
			fileMap.put(keyname[1], files);
		}
		return fileMap;
	}

}
